<template>
  <div class="user-login" >
    <div class="main-header">
      <!-- <a href class="main-header-logo">
        <img :src="logo" alt />
        <span>我爱报销</span>
      </a> -->
    </div>
    <div class="login-box">
      <div class="logo">
        <img :src="logo" alt style="width:180px;height:120px"/>
      </div>
      <van-tabs
        :border="false"
        v-model="active"
        color="#006CFF"
        line-width="50%"
        line-height="1"
        title-active-color="#006CFF"
        title-inactive-color="#979797"
      >
        <van-tab title="账号登录"></van-tab>
        <van-tab title="验证码登录"></van-tab>
      </van-tabs>
      <van-cell-group :border="false">
        <van-field
          @focus="onFocus"
          @blur="onBlur"
          v-model="phone"
          placeholder="请输入手机号1111111"
        >
          <template #label>
            +86
            <van-icon class="icon-arrow" name="arrow" />
          </template>
          <template v-if="active == 1" #right-icon>
            <span class="shou" style="color:#006cff" @click="isBool&&getVCode()">{{
              VCodeText
            }}</span>
          </template>
        </van-field>
        <!-- 密码输入框 -->
        <van-field
          v-if="active == 1"
          v-model="code"
          class="password-input"
          :border="false"
          :mask="false"
          :focused="showKeyboard"
          @focus="showKeyboard = true"
          placeholder="请输入验证码"
        />
        <van-field
          @keyup.enter="login()"
          type="password"
          v-if="active == 0"
          @focus="onFocus"
          @blur="onBlur"
          v-model="password"
          placeholder="请输入密码"
        />
      </van-cell-group>

      <div class="agreement" @click="isChecked = !isChecked">
        <template v-if="active == 1">
          <van-checkbox v-model="isChecked" shape="square" icon-size="14"
            >我已阅读且同意相关</van-checkbox
          >
          <router-link
            :to="{ path: '/agreement', name: 'Agreement', params: {phone:  phone, code: code} }"
            tag="span"
            style="font-weight: 700;"
            >《服务条款》和《隐私政策》</router-link
          >
        </template>
      </div>
      <!-- <div class="agreement1" @click="isChecked=!isChecked" v-if="this.active == 0"></div> -->

      <div>
        <van-checkbox v-model="isRememberPwd" shape="square" icon-size="14"
            >记住密码</van-checkbox
          >
      </div>

      <div class="log_div">
        <button @click="login()" class="log_btn">登录</button>
      </div>
      <div class="recBottom">
        <div></div>
        <div @click="forgetPwd">忘记密码</div>
        <!-- <div @click="registered">立即注册</div> -->
        <!-- <div>如何加入推广人计划?</div> -->
      </div>
    </div>
    <center style="width: 100%;font-size:16px">
      <div>Copyright © 2019 IBX.All Rights Reserved.</div>
      <div>鄂ICP备20002759号-2</div>
      <!-- <div>
        <img src alt />武汉溟宇科惠知识产权服务有限公司
      </div> -->
    </center>

    <!-- 数字键盘 -->
    <!-- <van-number-keyboard
      :show="showKeyboard"
      @input="onInput"
      @delete="onDelete"
      @blur="showKeyboard = false"
    ></van-number-keyboard> -->
  </div>
</template>

<script>
import { validation } from "@/utils/validate.js";
import { codeLogin, getCode, pwdLogin } from "@/api/login";
import { Dialog, Toast } from "vant";
import config from '../../api/config'
import axios from "axios"
import {get,post} from "../../api/query"
export default {
  data() {
    return {
      phone: "",
      password: "",
      code: "",
      active: 0,
      loginType: 0,
      isSelectUserType: true,
      isChecked: false,
      showKeyboard: false,
      VCodeText: "获取验证码",
      isAutoLogin: false,
      logo: require("@/assets/img/login_logo.png"),
      isRememberPwd: false,
      isBool:true
    };
  },
  created() {
    this.isBool = true
    if (this.$route.query.phone) {
      this.phone = atob(this.$route.query.phone);
    }
    if (this.$route.params.phone) {
      this.phone = atob(this.$route.params.phone);
    }
    if (this.$route.params.active) {
      this.active = Number(this.$route.params.active)
    }
    if (this.$route.params.code) {
      this.code = this.$route.params.code
    }
    if(JSON.parse(localStorage.getItem("$errandAccountPassword"))){
        let accountPassword = JSON.parse(localStorage.getItem("$errandAccountPassword"));
    
    if (accountPassword.isRememberPwd) {
      this.phone = window.atob(accountPassword.phone);
      this.password = window.atob(accountPassword.password);
      this.isRememberPwd = accountPassword.isRememberPwd;
    }
    }
    console.log(config.get("v"));
  },
  computed: {
    btoaPhone () {
      return btoa(this.phone)
    }
  },
  mounted() {},
  //缓存也会走的钩子
  deactivated() {
    this.$destroy(true); //销毁组件
  },
  methods: {
    registered() {
      this.$router.push("/register");
    },
    forgetPwd() {
      this.$router.push("/forgetPwd");
    },
    onInput(key) {
      this.code = (this.code + key).slice(0, 6);
    },
    onDelete() {
      this.code = this.code.slice(0, this.code.length - 1);
    },
    onFocus(data) {
      data.path[3].style["border-color"] = "#006CFF";
    },
    onBlur(data) {
      data.path[3].style["border-color"] = "#ebedf0";
    },
    // 登录
    login() {
      if (!this.isChecked && this.active == 1) {
        Dialog.alert({
          title: "提示",
          message: "请勾选并阅读相关服务条款和隐私政策！"
        });
        return;
      }
      //效验
      let validationError = "";
      if (this.active == 0) {
        validationError = validation({
          isPassword: true,
          phone: this.phone,
          password: this.password
        });
      } else {
        validationError = validation({
          isPassword: false,
          phone: this.phone,
          verificationCode: this.code
        });
      }

      console.log(this.code)
      if (validationError === "") {
        //TODO:验证通过
        // 用户登录
        if (this.active == 0) {
          // 账号密码登录
          const params = {
            phone: this.phone,
            password: this.password
          };
          this.pwdLoginPost(params);
        } else {
          // 验证码登录
          const params = {
            tel: this.phone,
            code: this.code
          };
          this.codeLoginPost(params);
        }
      } else {
        Dialog.alert({
          title: "提示",
          message: validationError
        });
      }
    },
    pwdLoginPost(params) {
    axios.get(config.get('bpp_url')+config.get('v')+'_login',{params})
        // pwdLogin(params)
        .then(res => {
            res = res.data
          if (res.code == 200) {
            console.log(res,'res')
            if (res.data.user.role_id == 3) {
              var url = config.get("bpp_url")
              this.$store.commit("setToken", res.data.token);
              this.$store.commit("setUser", res.data.user);
              config.setUserInfo(res.data);
              sessionStorage.setItem("token", res.data.token);
              // 判断是否有OA账号 首页给提示
            //   sessionStorage.setItem("isOATipOver",res.data.expand_info[0].oa_phone && res.data.expand_info[0].oa_pwd ? true: false);
              //判断是否实名认证
              sessionStorage.setItem("isSmrzOver", res.data.errands_info && res.data.errands_info[0].id_card_number ? true : false);
              let $accountPassword = {
              phone: window.btoa(params.phone),
              password: window.btoa(params.password),
              isRememberPwd: this.isRememberPwd
              };
              localStorage.setItem(
                "$errandAccountPassword",
                JSON.stringify($accountPassword)
              );
              axios.get(url+'sys_init').then(res=>{
                window.localStorage.setItem(config.get('v')+'_init',JSON.stringify(res.data.data.apireg))
                this.$router.replace("/replace");
              })
            }else{
              this.$message.warning('请使用代报员账号登录')
            }
            // else {
            //   this.$router.replace("/user/home");
            // }
          }else{
          this.password = "";
          }
        })
    },
    codeLoginPost(params) {
    //   codeLogin(params).then(res => {
        get('userCodeLogin',params,res=>{
        if (res.code == 200) {
          this.$store.commit("setToken", res.data.token);
          this.$store.commit("setUser", res.data.user);
          sessionStorage.setItem("token", res.data.token);
          // this.$message.success("欢迎您！");
          // 判断是否有OA账号 首页给提示
        //   sessionStorage.setItem("isOATipOver",res.data.expand_info[0].oa_phone && res.data.expand_info[0].oa_pwd ? true: false);
          //判断是否实名认证
          sessionStorage.setItem("isSmrzOver", res.data.errands_info && res.data.errands_info[0].id_card_number ? true : false);
          if (res.data.user.role_id == 3) {
            this.$router.replace("/replace");
          }else{
            this.$message.warning('请使用代报员账号登录')
          }
          // else {
          //   this.$router.replace("/user/home");
          // }
        } else {
          Dialog.alert({
            title: "提示",
            message: res.data
          });
        }
      });
    },

    // 获取验证码
    getVCode() {
      if (!this.isChecked) {
        Dialog.alert({
          title: "提示",
          message: "请勾选并阅读相关服务条款和隐私政策！"
        });
        return;
      }
      let that = this;
      if (/^1[3456789]\d{9}$/.test(that.phone)) {
        let params = {};
        params = {
          tel: that.phone
        };
        // getCode(params).then(res => {
        get('getCodeLogin',params,res=>{
          if (res.code === 200) {
            this.$message.success("验证码发送成功！请注意查收。");
            let num = 60;
            that.btnIsDisabled = true;
            const timer = setInterval(function() {
              that.VCodeText = num + "秒后可重新发送";
              num -= 1;
              if (num < 0) {
                that.isBool = true
                that.VCodeText = "发送验证码";
                that.btnIsDisabled = false;
                clearInterval(timer);
              }
            }, 1000);
          } else {
            this.$message.error("验证码发送失败！");
            that.btnIsDisabled = false;
            clearInterval(timer);
          }
        });
        this.isBool = false
      } else {
        Dialog.alert({
          title: "提示",
          message: "手机号不能为空且格式不能有误"
        });
      }
    },
    // 注册
    onRegister() {
      this.$router.push("register");
    }
  },
  watch: {
    code: function(value) {
      if (/^[\d]{6}$/.test(value)) {
        this.login();
      }
    }
  }
};
</script>

<style lang="less">
.log_div{
  width: 50%;
    margin:30px auto 10px;
  .log_btn{
  width: 100%;
  border: none;
  background:#006CFF;
  height: 45px;
  color: #fff;
  cursor: pointer;
  border-radius: 15px;
  font-weight: 400;
  font-size: 18px;
  &:hover{
    opacity: .8;
  }
}
}

.van-cell.van-field{
  border-width: 1px;
}
.van-field__label {
  display: flex;
  align-items: center;
  font-size: 14px;
  width: 20px;
}

.van-tab__text--ellipsis {
  font-size: 20px;
}

.van-password-input {
  margin: 0;
  margin-bottom: 10px;

  .password-input {
    // height: .96rem;
    // line-height: .96rem;

    &::after {
      border: none;
    }

    li {
      
      border-bottom: 1px solid #ebedf0;
      
      margin-right: 11px;
      box-sizing: border-box;
      // line-height: .96rem;

      &:last-child {
        margin-right: 0;
      }

      &::after {
        border: none;
      }
    }
  }
}

.van-cell {
  align-items: center;
  height: 60px;
  border-bottom: 0.026667rem solid #ebedf0;
}

.van-password-input {
  height: 50px;
}

.user-login {
  width: 100%;
  height: 100%;
  padding: 0.8rem 0.666667rem;
  box-sizing: border-box;
  color: #353535;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-top: -120px;
  .header-title {
    width: 100%;
    position: fixed;
    left: 0;
    top: 0;
    height: 1.333333rem;
    line-height: 1.333333rem;
    font-size: 0.533333rem;
    text-align: center;
    font-weight: 700;

    > div {
      height: 0.266667rem;
      background-color: #f5f5f5;
    }
  }

  .select-box {
    height: 100%;
  }

  .selct-user-type {
    display: flex;
    flex-direction: column;
    justify-content: center;
    height: 100%;
    text-align: center;

    .title {
      font-weight: 700;
      font-size: 0.533333rem;
      margin-bottom: 1.866667rem;
    }

    .icon-box {
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      color: #000;

      &:nth-child(1) {
        margin-bottom: 1.333333rem;
      }

      &:nth-child(2) {
        margin-top: 1.333333rem;
      }

      img {
        margin-bottom: 0.253333rem;

        &:first-child {
          width: 3.586667rem;
          height: 3.266667rem;
        }

        &:last-child {
          width: 3.266667rem;
          height: 3.804933rem;
        }
      }

      > div {
        width: 3.2rem;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 0.426667rem;

        &:last-child {
          // margin-bottom: 1.6rem;
        }

        > span {
          display: inline-block;
          width: 0.426667rem;
          height: 0.426667rem;
          border-radius: 50%;
          border: 0.026667rem solid #006cff;
          margin-right: 0.266667rem;
        }

        > span.active {
          position: relative;

          &::after {
            position: absolute;
            left: 0.08rem;
            top: 0.08rem;
            content: "";
            width: 0.266667rem;
            height: 0.266667rem;
            border-radius: 50%;
            background-color: #006cff;
          }
        }
      }
    }
  }

  .login-box {
    position: relative;
    width: 30%;
    height: 50%;
    display: flex;
    margin: auto;
    flex-direction: column;
    justify-content: center;

    .get-code-btn {
      color: #006cff;
      font-size: 0.373333rem;
      height: 0.96rem;
      line-height: 0.96rem;
      border: none;
      background-color: #fff;
      padding: 0;
    }

    .check-box {
      border: 0.026667rem solid #006cff;
    }

    .agreement {
      display: flex;
      align-items: center;
      line-height: 17px;
      font-size: 12.5px;
      height: 65px;
      margin-top: 10px;
      box-sizing: border-box;
    }
    .recBottom {
      margin-top: 15px;
      display: flex;
      flex-direction: row;
      justify-content: space-between;

      div {
        cursor: pointer;
        color: #006cff;
        font-size: 14px;
      }
    }
    >.logo {
      margin: 15px auto;
    }
  }

  .button,
  .login-button {
    width: 100%;
    height: 1.2rem;
    line-height: 1.2rem;
    font-size: 0.426667rem;
  }

  .button {
    margin-top: 0.4rem;
  }

  center {
    position: fixed;
    bottom: 0;
    left: 0;
    padding: 20px 0 20px 0;
    box-sizing: border-box;
    font-size: 0.32rem;
  }
  .main-header {
    left: 0;
  }
}
</style>
